(function() {
	if(!$){console.log("please import 'jquery.js' first!!"); return;}
	if(!IScroll){console.log("please import 'iscroll.js' first!!"); return;}
	
	function XYScroller(el, list, ops){
		var defaultOps = {scrollbars:true, fadeScrollbars:true, probeType:2, 
			pullDownLabel:"下拉刷新", pullDownMoveLabel:"松开刷新", pullDownLoadingLabel:"加载中....",
			pullUpLabel:"加载更多", pullUpMoveLabel:"释放加载", pullUpLoadingLabel:"加载中....", noMoreLoadLabel:"已经到最后"
		};
		ops = $.extend(defaultOps, ops);
		
		$(el).addClass("xy_scroller_wrapper");
		this.$pdElem = $(el).find(".xy_scroller_pulldown");
		this.$puElem = $(el).find(".xy_scroller_pullup");
		if(this.$pdElem.length > 0)
		{
			this.$pdElem.css("top",-this.$pdElem.height());
		}
		if(this.$puElem.length > 0)
		{
			this.$puElem.css("bottom",-this.$puElem.height());
		}
		
		this.$list = $(list);
		if(this.$list.length > 0)
		{
			this.$template = $(this.$list.children()[0]).clone(true);
			this.$list.empty();
		}
		
		this.iscroll = new IScroll(el, ops);
		this.iscroll.xyScroller = this;
		this.iscroll.on("scroll",this.onScrollMove);
		this.iscroll.on("scrollEnd",this.onScrollEnd);
	}
	
	XYScroller.prototype = {
		state:0,//0为普通状态；1为开始刷新列表；2为开始加载更多
		
		onScrollMove:function(){
			var scroller = this.xyScroller;
			if(scroller.state !== 0)return;
			var $pdElem = scroller.$pdElem, $puElem = scroller.$puElem;
			
			if($pdElem.length > 0 && this.y > $pdElem.height())
			{
				$pdElem.text(this.options.pullDownMoveLabel);
				scroller.state = 1;
			}
			else if($puElem.length > 0 && this.y < this.maxScrollY - $puElem.height())
			{
				$puElem.text(this.options.pullUpMoveLabel);
				scroller.state = 2;
			}
		},
		
		onScrollEnd:function(){
			var scroller = this.xyScroller,
			ops = this.options;
			if(scroller.state === 1)
			{
				scroller.$pdElem.text(ops.pullDownLabel);
				scroller.refresh();
			}
			else if(scroller.state === 2)
			{
				scroller.$puElem.text(ops.pullUpLabel);
				ops.onLoadMore && ops.onLoadMore(this.wrapper);
			}
			scroller.state = 0;
		},
		
		refresh:function(d){
			if(this.$list.length === 0)return;
			
			if($.isArray(d))
			{
				this.$list.empty();
				this.addListItems(d);
			}
			else
			{
				this.iscroll.options.onRefresh && this.iscroll.options.onRefresh();
			}
		},
		
		addListItem:function(data, needRefresh){
			if(this.$list.length === 0)return;
			if(needRefresh === undefined)needRefresh = true;
			var $cl = this.$template.clone(true);
			this.iscroll.options.onAddListItem && this.iscroll.options.onAddListItem($cl,data);
			this.$list.append($cl);
			if(needRefresh)this.iscroll.refresh();
		},
		
		addListItems:function(dAry){
			if(this.$list.length === 0)return;
			var len = dAry.length;
			for(var i=0;i<len;i++)this.addListItem(dAry[i], false);
			this.iscroll.refresh();
		}
	}
	
	window.XYScroller = XYScroller;
})();